package com.huicoo.forestmanager.network;


import android.text.TextUtils;
import android.webkit.MimeTypeMap;

import com.huicoo.forestmanager.CustomUtils;
import com.huicoo.forestmanager.network.api.ApiService;
import com.huicoo.forestmanager.network.api.RequestUrl;
import com.huicoo.forestmanager.network.bean.alarm.AlarmBean;
import com.huicoo.forestmanager.network.bean.login.LoginResData;
import com.huicoo.forestmanager.network.bean.patrol.AttachmentEntity;
import com.huicoo.forestmanager.network.bean.patrol.AutoinfoBean;
import com.huicoo.forestmanager.network.bean.patrol.EventTypeBean;
import com.huicoo.forestmanager.network.bean.patrol.GetMyForestZoneBean;
import com.huicoo.forestmanager.network.bean.patrol.GetReportTimeSpanBean;
import com.huicoo.forestmanager.network.bean.patrol.GetquerymonthBean;
import com.huicoo.forestmanager.network.bean.patrol.GetrecordschemeBean;
import com.huicoo.forestmanager.network.bean.patrol.PatrolTaskReportPositionBean;
import com.huicoo.forestmanager.network.bean.patrol.PatrolToDoList;
import com.huicoo.forestmanager.network.bean.patrol.RecordDetailsIssuesListBean;
import com.huicoo.forestmanager.network.bean.patrol.RecorddetailsBean;
import com.huicoo.forestmanager.network.bean.patrol.RecordlistBean;
import com.huicoo.forestmanager.network.bean.patrol.ReportEventBean;
import com.huicoo.forestmanager.network.bean.patrol.ReportrecordinfoBean;
import com.huicoo.forestmanager.network.bean.patrol.StartPatrolBean;
import com.huicoo.forestmanager.network.bean.patrol.StopPatrolBean;
import com.huicoo.forestmanager.network.bean.patrol.UploadFileBean;
import com.huicoo.forestmanager.network.bean.patrol.VerifyEventBean;
import com.huicoo.forestmanager.network.bean.patrol.VerifyEventCommentBean;
import com.huicoo.forestmanager.network.cookie.CookieManager;
import com.huicoo.forestmanager.others.Constants;
import com.huicoo.forestmanager.util.JsonUtils;
import com.huicoo.forestmanager.util.LogUtils;
import com.huicoo.forestmanager.util.SharedPreferenceUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


public class HttpService {
    private String baseUrl;
    private ApiService apiService;

    private static class Wrapper {
        static HttpService httpService = new HttpService();

        static void initService() {
            httpService = new HttpService();
        }
    }

    private HttpService() {
        String mBaseUrl = SharedPreferenceUtil.LoadStringData(Constants.PROJECT_NAME, Constants.BASE_URL);
        if (TextUtils.isEmpty(mBaseUrl)) {
            //防止无url情况
            baseUrl = "http://47.110.80.118:8003/";
        } else {
            baseUrl = mBaseUrl;
        }
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(chain -> {
                    String appId = SharedPreferenceUtil.LoadStringData(Constants.PROJECT_NAME, Constants.UNIQUE_ID);
                    Request request = chain.request()
                            .newBuilder()
                            .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                            .addHeader("Accept-Encoding", "gzip, deflate")
                            .addHeader("Connection", "keep-alive")
                            .addHeader("Accept", "*/*")
                            .addHeader("appid", appId)
                            .build();
                    return chain.proceed(request);
                }).connectTimeout(60, TimeUnit.SECONDS)
                .cookieJar(new CookieManager()).build();
        Retrofit retrofit = new Retrofit.Builder().baseUrl(baseUrl)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        apiService = retrofit.create(ApiService.class);
    }

    public static HttpService getInstance() {
        return Wrapper.httpService;
    }

    public static void resetHttpService() {
        Wrapper.initService();
    }

    public Call<LoginResData> login(String account, String password) {
        LogUtils.v("gogogo login url = " + baseUrl + RequestUrl.login);
        return apiService.login(account, password);
    }


    //	获取待巡林班列表
    public Call<PatrolToDoList> patrolToDoList() {
        HashMap<String, String> patrolToDoList = new HashMap<>();
        patrolToDoList.put("userId", CustomUtils.getUserID());
        patrolToDoList.put("Token", CustomUtils.getToken());
        return apiService.patrolToDoList(patrolToDoList);
    }

    //	通过林班id获取待巡林班列表
    public Call<PatrolToDoList> patrolToDoList(HashMap<String, String> params) {
        LogUtils.v("gogogo patrol task to do list url = " + baseUrl + RequestUrl.patrolTaskReportPosition);
        LogUtils.v("gogogo patrol task to do list params = " + JsonUtils.toJson(params));
        return apiService.patrolToDoList(params);
    }

    //获取巡查记录月份
    public Call<GetquerymonthBean> getquerymonth() {
        HashMap<String, String> patrolToDoList = new HashMap<>();
        patrolToDoList.put("Token", CustomUtils.getToken());
        return apiService.getquerymonth(patrolToDoList);
    }


    //获取巡查记录
    public Call<RecordlistBean> getrecordlist(String time) {
        HashMap<String, String> patrolToDoList = new HashMap<>();
        patrolToDoList.put("Token", CustomUtils.getToken());
        patrolToDoList.put("Time", time);
        LogUtils.v("gogogo record = " + JsonUtils.toJson(patrolToDoList));
        return apiService.getrecordlist(patrolToDoList);
    }


    //获取巡查详细信息
    public Call<RecorddetailsBean> getrecorddetails(int recordID) {
        HashMap<String, String> getrecorddetails = new HashMap<>();
        getrecorddetails.put("Token", CustomUtils.getToken());
        getrecorddetails.put("RecordID", recordID + "");  //巡查ID
        return apiService.getrecorddetails(getrecorddetails);
    }

    //巡查详情问题列表
    public Call<RecordDetailsIssuesListBean> getRecordDetailsIssuesList(int recordID) {
        HashMap<String, String> getrecorddetails = new HashMap<>();
        getrecorddetails.put("Token", CustomUtils.getToken());
        getrecorddetails.put("RecordID", recordID + "");  //巡查ID
        getrecorddetails.put("PageIndex", "1");
        getrecorddetails.put("PageSize", "500");
        LogUtils.v("gogogo get record detail issues url = " + baseUrl + RequestUrl.getRecordDetailsIssuesList);
        LogUtils.v("gogogo get record detail issues params = " + JsonUtils.toJson(getrecorddetails));
        return apiService.getRecordDetailsIssuesList(getrecorddetails);
    }


    // 开始巡查
    public Call<StartPatrolBean> patrolTaskStart(HashMap<String, String> params) {
        LogUtils.v("gogogo patrol start task url = " + baseUrl + RequestUrl.patrolTaskStart);
        LogUtils.v("gogogo patrol start task params = " + JsonUtils.toJson(params));
        return apiService.patrolTaskStart(params);
    }

    // 巡查任务上报位置
    public Call<PatrolTaskReportPositionBean> patrolTaskReportPosition(HashMap<String, String> params) {
        LogUtils.v("gogogo patrol task report position url = " + baseUrl + RequestUrl.patrolTaskReportPosition);
        LogUtils.v("gogogo patrol task report position params = " + JsonUtils.toJson(params));
        return apiService.patrolTaskReportPosition(params);
    }

    // 结束巡查
    public Call<StopPatrolBean> patrolTaskStop(HashMap<String, String> params) {
        LogUtils.v("gogogo patrol stop task url = " + baseUrl + RequestUrl.patrolTaskStop);
        LogUtils.v("gogogo patrol stop task params = " + JsonUtils.toJson(params));
        return apiService.patrolTaskStop(params);
    }

    // 获取事件类型
    public Call<EventTypeBean> getEventType(HashMap<String, String> params) {
        LogUtils.v("gogogo get event type url = " + baseUrl + RequestUrl.getEventType);
        LogUtils.v("gogogo get event type params = " + JsonUtils.toJson(params));
        return apiService.getEventType(params);
    }

    // 上传附件
    public Call<UploadFileBean> uploadFile(HashMap<String, String> params, AttachmentEntity attachmentEntity) {
        LogUtils.v("gogogo upload file url = " + baseUrl + RequestUrl.uploadFile);
        LogUtils.v("gogogo upload file params = " + JsonUtils.toJson(params));
        List<AttachmentEntity> fileList = new ArrayList<>();
        fileList.add(attachmentEntity);
        HashMap<String, RequestBody> fileMap = getMultipartParams(params, fileList);
        return apiService.uploadFile(fileMap);
    }

    // 事件上报
    public Call<ReportEventBean> reportEvent(HashMap<String, String> params) {
        LogUtils.v("gogogo report event url = " + baseUrl + RequestUrl.reportEvent);
        LogUtils.v("gogogo report event params = " + JsonUtils.toJson(params));
        return apiService.reportEvent(params);
    }

    // 下载附件
    public Call<ResponseBody> downloadFile(String fileUrl) {
        LogUtils.v("gogogo download file url = " + fileUrl);
        return apiService.downloadFile(fileUrl);
    }

    // 事件回复
    public Call<VerifyEventBean> replyEvent(HashMap<String, String> params) {
        LogUtils.v("gogogo reply event url = " + baseUrl + RequestUrl.replyEvent);
        LogUtils.v("gogogo reply event params = " + JsonUtils.toJson(params));
        return apiService.replyEvent(params);
    }

    // 事件核实
    public Call<VerifyEventBean> verifyEvent(HashMap<String, String> params) {
        LogUtils.v("gogogo verify event url = " + baseUrl + RequestUrl.verifyEvent);
        LogUtils.v("gogogo verify event params = " + JsonUtils.toJson(params));
        return apiService.verifyEvent(params);
    }

    // 获取事件评论
    public Call<VerifyEventCommentBean> getComment(HashMap<String, String> params) {
        LogUtils.v("gogogo get comment url = " + baseUrl + RequestUrl.getEventComment);
        LogUtils.v("gogogo get comment params = " + JsonUtils.toJson(params));
        return apiService.getComment(params);
    }

    // 获取本次任务上报的事件
    public Call<RecordDetailsIssuesListBean> getMyReportEvent(HashMap<String, String> params) {
        LogUtils.v("gogogo get my report event url = " + baseUrl + RequestUrl.getRecordDetailsIssuesList);
        LogUtils.v("gogogo get my report event params = " + JsonUtils.toJson(params));
        return apiService.getMyReportEvent(params);
    }

    // 警情上报
    public Call<AlarmBean> alarm(HashMap<String, String> params) {
        LogUtils.v("gogogo alarm url = " + baseUrl + RequestUrl.alarm);
        LogUtils.v("gogogo alarm params = " + JsonUtils.toJson(params));
        return apiService.alarm(params);
    }

    //获取林长责任林地信息
    public Call<GetMyForestZoneBean> getMyForestZone(HashMap<String, String> params){
        LogUtils.v("gogogo get my forest zone url = " + baseUrl + RequestUrl.getMyForestZone);
        LogUtils.v("gogogo get my forest zone params = " + JsonUtils.toJson(params));
        return apiService.getMyForestZone(params);
    }

    // 获取巡查任务详情
    public Call<RecorddetailsBean> getTaskDetails(HashMap<String, String> params) {
        LogUtils.v("gogogo get task details url = " + baseUrl + RequestUrl.getrecorddetails);
        LogUtils.v("gogogo get task details params = " + JsonUtils.toJson(params));
        return apiService.getrecorddetails(params);
    }

    // 获取巡查任务上报位置间隔时间
    public Call<GetReportTimeSpanBean> getReportTimeSpan(HashMap<String, String> params) {
        LogUtils.v("gogogo get task report time url = " + baseUrl + RequestUrl.getReportTimeSpan);
        LogUtils.v("gogogo get task report time params = " + JsonUtils.toJson(params));
        return apiService.getReportTimeSpan(params);
    }

    private HashMap<String, RequestBody> getMultipartParams(HashMap<String, String> params, List<AttachmentEntity> fileList) {
        HashMap<String, RequestBody> fileMap = new HashMap<>();
        Set<Map.Entry<String, String>> entrys = params.entrySet();
        for (Map.Entry<String, String> entry : entrys) {
            RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), entry.getValue());
            fileMap.put(entry.getKey(), body);
        }

        for (AttachmentEntity entity : fileList) {
            RequestBody requestFile;
            String mediaType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(entity.file.getAbsolutePath()));
            LogUtils.v("gogogo attachment type = " + mediaType);
            if (entity.attachmentType == 1) {
                requestFile = RequestBody.create(MediaType.parse(mediaType), entity.file);
            } else if (entity.attachmentType == 2) {
                requestFile = RequestBody.create(MediaType.parse("image/*"), entity.file);
            } else {
                requestFile = RequestBody.create(MediaType.parse("video/*"), entity.file);
            }
            //注意：file就是与服务器对应的key,后面filename是服务器得到的文件名
            fileMap.put("file\"; filename=\"" + entity.fileName, requestFile);
        }
        return fileMap;
    }



    //根据登录账号获取巡查方案
    public Call<GetrecordschemeBean> getrecordscheme() {
        HashMap<String, String> patrolToDoList = new HashMap<>();
        patrolToDoList.put("Token", CustomUtils.getToken());
        return apiService.getrecordscheme(patrolToDoList);
    }

    //巡查记录报送
    public Call<ReportrecordinfoBean> reportrecordinfo(String weather, String position, String recordsituation, String dealresult, String remark, String recordID) {
        HashMap<String, String> patrolToDoList = new HashMap<>();
        patrolToDoList.put("Token", CustomUtils.getToken());
        patrolToDoList.put("weather",weather);//天气
        patrolToDoList.put("position", position);//巡山地点
        patrolToDoList.put("recordsituation", recordsituation);//巡护情况
        patrolToDoList.put("dealresult", dealresult);//处理结果（会提供一个获取处理结果类型的接口）
        patrolToDoList.put("remark", remark);//备注
        patrolToDoList.put("RecordID", recordID+"");//巡查ID
        return apiService.reportrecordinfo(patrolToDoList);
    }


    //获取巡查自动填报信息
    public Call<AutoinfoBean> getautoinfo(String recordID) {
        HashMap<String, String> patrolToDoList = new HashMap<>();
        patrolToDoList.put("Token", CustomUtils.getToken());
        patrolToDoList.put("RecordID", recordID+"");//巡查ID
        return apiService.getautoinfo(patrolToDoList);
    }

}
